import api from './api';
import { MainAppConfig, UserInfo, QuotaInfo } from '../types/mainApp';
import { ApiResponse } from '../types/auth';
import { AccountInfo } from '../types/account';
import { AxiosResponse } from 'axios';

// The API can return either a real account or a confirmation request.
type AccountResponse = AccountInfo | {
    confirmation_required: true;
    current_account_details: {
        requestUsage?: number;
        maxRequestUsage?: number;
    };
};

/**
 * 获取应用配置
 * @returns Promise<AxiosResponse<ApiResponse<MainAppConfig>>>
 */
export const getMainAppConfig = (): Promise<AxiosResponse<ApiResponse<MainAppConfig>>> => {
    return api.get('/app/config');
};

/**
 * 获取当前登录用户的信息
 * @returns Promise<AxiosResponse<ApiResponse<UserInfo>>>
 */
export const getCurrentUserInfo = (): Promise<AxiosResponse<ApiResponse<UserInfo>>> => {
    return api.get('/user/current');
};

/**
 * 激活卡密
 * @param code 卡密字符串
 * @returns Promise<AxiosResponse<ApiResponse<QuotaInfo>>>
 */
export const activateCode = (code: string): Promise<AxiosResponse<ApiResponse<QuotaInfo>>> => {
    return api.post('/activation-code/activate', { code });
};

/**
 * 从服务器获取一个可用的池账号
 * @param maliceSwitch - 是否是用户确认后的强制切换
 * @returns Promise<AxiosResponse<ApiResponse<AccountInfo>>>
 */
export const getAvailableAccount = (maliceSwitch = false): Promise<AxiosResponse<ApiResponse<AccountResponse>>> => {
    return api.post('/account/available', { malice_switch: maliceSwitch })
        .catch(error => {
            // This special handling lets the component intercept the confirmation "error".
            if (error.response?.status === 290) {
                throw error; // Re-throw to be caught by the calling component
            }
            // For all other errors, also re-throw.
            throw error;
        });
}; 